package com.example.teststarter.designpattern;

import java.util.HashMap;
import java.util.Map;

/**
 * 享元工厂
 */
public class LibraryFactory {

    /**
     * 图书馆维护一个图书列表
     */
    private Map<String, Book> bookPools = new HashMap<>();

    private static LibraryFactory factory = new LibraryFactory();

    /**
     * 图书馆只有一个
     */
    public static LibraryFactory getInstance() {
        return factory;
    }

    /**
     * 图书馆外借图书
     */
    public Book libToBorrow(String bookName) {
        Book book;
        //如果书架有书，直接借出
        if (bookPools.containsKey(bookName)) {
            book = bookPools.get(bookName);
        } else {
            //如果没有,那就拿本新书
            //根据外部状态创建享元对象
            book = new ConcreteBook(bookName);
            //放到池中
            bookPools.put(bookName, book);
        }
        return book;
    }

    /**
     * 书架上书的数量
     */
    public int getAllBookSize() {
        return bookPools.size();
    }
}
